﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Net;
using mojoPortal.Web.Framework;
using mojoPortal.Web;
using ud_Article.Business;
using Resources;
using System.Collections.Generic;
using ud_Utilities;

namespace ud_Article.UI
{
    public partial class BlogViewControl : UserControl
    {
        #region Properties

        private Hashtable moduleSettings;
        protected ArticleConfiguration config = new ArticleConfiguration();
        private Article article;
        private List<Business.ud_Article> otherArticles;
        private Module module;
        protected string DeleteLinkImage = "~/Data/SiteImages/" + WebConfigSettings.DeleteLinkImage;
        ud_ArticleCategory category = new ud_ArticleCategory();
        private const string newWindowMarkup = "onclick=\"window.open(this.href, '', 'resizable=no,status=no,location=no,toolbar=no,menubar=no,fullscreen=no,scrollbars=no,dependent=no');return false;\"";
        protected int PageId = -1;
        protected int ModuleId = -1;
        protected int ItemId = -1;
        protected bool AllowComments;

        protected string CommentDateTimeFormat;
        protected bool parametersAreInvalid;
        protected Double TimeOffset;
        private TimeZoneInfo timeZone;

        protected bool IsEditable;
        protected string EditContentImage = ConfigurationManager.AppSettings["EditContentImage"];
        protected string GmapApiKey = string.Empty;

        protected string blogAuthor = string.Empty;
        protected string SiteRoot = string.Empty;
        protected string ImageSiteRoot = string.Empty;
        private mojoBasePage basePage;

        private string DisqusSiteShortName = string.Empty;
        private string IntenseDebateAccountId = string.Empty;

        protected string RegexRelativeImageUrlPatern = @"^/.*[_a-zA-Z0-9]+\.(png|jpg|jpeg|gif|PNG|JPG|JPEG|GIF)$";
        readonly DBArticleCategory repository = new DBArticleCategory();

        #endregion

        #region OnInit

        override protected void OnInit(EventArgs e)
        {
            Load += Page_Load;
            btnPostComment.Click += btnPostComment_Click;
            dlComments.ItemCommand += dlComments_ItemCommand;
            dlComments.ItemDataBound += dlComments_ItemDataBound;
            dpOtherArticles.PreRender += dpOtherArticles_PreRender;
            rptAttachments.ItemDataBound += rptAttachments_ItemDataBound;
            base.OnInit(e);
            //EnableViewState = UserCanEditPage();
            basePage = Page as mojoBasePage;
            if (basePage == null) return;
            SiteRoot = basePage.SiteRoot;
            ImageSiteRoot = basePage.ImageSiteRoot;
        }

        #endregion

        private void Page_Load(object sender, EventArgs e)
        {
            Page.EnableViewState = true;
            LoadParams();

            if (
                (basePage == null)
                || (!basePage.UserCanViewPage(ModuleId))
            )
            {
                SiteUtils.RedirectToAccessDeniedPage();
                return;
            }

            if (parametersAreInvalid)
            {
                AllowComments = false;
                pnlBlog.Visible = false;
                return;
            }
            LoadSettings();
            //SetupCss();
            //SetupRssLink();
            PopulateLabels();
            if(config.AllowComments)
            {
                SetupJqueryComments();
            }
            if (IsPostBack || ModuleId <= -1 || ItemId <= 0) return;
            if (Context.User.Identity.IsAuthenticated)
            {
                if (WebUser.HasEditPermissions(basePage.SiteInfo.SiteId, ModuleId, basePage.CurrentPage.PageId))
                {
                    IsEditable = true;
                }
            }

            PopulateControls();
        }

        private void SetupJqueryComments()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<script type='text/javascript'>");
            sb.Append("$(document).ready(function(){");
            sb.Append("$('.feedbacktrigger" + ModuleId + "').toggle(function(){");
            
            sb.Append("$('.feedback" + ModuleId + "').slideToggle();");
            
            sb.Append("}, function(){");
            
            sb.Append("$('.feedback" + ModuleId + "').slideToggle();");
            
            sb.Append("});");
            sb.Append("});");
            sb.Append("</script>");
            if(!Page.ClientScript.IsStartupScriptRegistered(typeof(Page), "feedback" + ModuleId))
            {
                Page.ClientScript.RegisterStartupScript(typeof(Page), "feedback" + ModuleId, sb.ToString());
            }
        }

        
        void dpOtherArticles_PreRender(object sender, EventArgs e)
        {
            BindOtherArticles();
        }

        protected virtual void PopulateControls()
        {
            captcha.ProviderName = basePage.SiteInfo.CaptchaProvider;
            captcha.Captcha.ControlID = "captcha" + ModuleId.ToInvariantString();
            captcha.RecaptchaPrivateKey = basePage.SiteInfo.RecaptchaPrivateKey;
            captcha.RecaptchaPublicKey = basePage.SiteInfo.RecaptchaPublicKey;

            if (parametersAreInvalid)
            {
                AllowComments = false;
                pnlBlog.Visible = false;
                return;
            }

            // if not published only the editor can see it
            if (
                ((!article.IsPublished) || (article.StartDate > DateTime.UtcNow))
                && (!basePage.UserCanEditModule(ModuleId))
                )
            {
                AllowComments = false;
                pnlBlog.Visible = false;
                WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
                return;
            }

            if (IsEditable)
            {
                lnkEdit.Visible = true;
                if (!basePage.UseTextLinksForFeatureSettings)
                {
                    lnkEdit.ImageUrl = basePage.ImageSiteRoot + "/Data/SiteImages/" + EditContentImage;
                    lnkEdit.Text = ArticleResources.EditImageAltText;
                }
                else
                {
                    lnkEdit.Text = ArticleResources.BlogEditEntryLink;
                }


                lnkEdit.NavigateUrl = basePage.SiteRoot + "/Article/EditPost.aspx?pageid="
                    + PageId.ToInvariantString()
                    + "&ItemID=" + ItemId.ToInvariantString()
                    + "&mid=" + ModuleId.ToInvariantString();


            }

            basePage.Title = SiteUtils.FormatPageTitle(basePage.SiteInfo, article.Title);
            basePage.MetaDescription = article.MetaDescription;
            basePage.MetaKeywordCsv = article.MetaKeywords;
            basePage.AdditionalMetaMarkup = article.CompiledMeta;
            if (basePage.AnalyticsSection.Length == 0)
            {
                basePage.AnalyticsSection = ConfigHelper.GetStringProperty("AnalyticsBlogSection", "blog");
            }
            litTitle.Text = Server.HtmlEncode(article.Title);

            if (article.ImageUrl != string.Empty)
            {
                string imgUrl = ImageSiteRoot + "/" + ConfigurationManager.AppSettings["ArticleImagesFolder"] + article.ImageUrl;
                image1.ImageUrl = ud_Utilities.Utilities.GetRealImageUrl(imgUrl);
                image1.AlternateText = article.Title;
            }
            else
            {
                image1.Visible = false;
            }

            tweetThis1.Visible = config.ShowTweetThisLink;
            tweetThis1.TitleToTweet = article.Title;


            fblike.Visible = config.UseFacebookLikeButton;
            fblike.ColorScheme = config.FacebookLikeButtonTheme;
            fblike.ShowFaces = config.FacebookLikeButtonShowFaces;
            fblike.HeightInPixels = config.FacebookLikeButtonHeight;
            fblike.WidthInPixels = config.FacebookLikeButtonWidth;

            fbshare.Url = Uri.EscapeUriString(SiteRoot + Request.RawUrl);
            fbshare.Visible = config.UseFacebookShareButton;
            fbshare.Title = Uri.EscapeUriString(article.Title);
            fbshare.ImgUrl = ImageSiteRoot + "/Data/Icon16x16/facebook.png";

            googleBookmark.Visible = config.UseGoogleBookmarkButton;
            googleBookmark.Url = Uri.EscapeUriString(SiteRoot + Request.RawUrl);
            googleBookmark.Title = Uri.EscapeUriString(article.Title);
            googleBookmark.ImgUrl = ImageSiteRoot + "/Data/Icon16x16/google.png";

            ltrGoTop.Text = config.GoToTop;
            imageGoTop.ImageUrl = ImageSiteRoot + "/Data/Icon16x16/Up.png";

            txtCommentTitle.Text = ArticleResources.CommentReply + article.Title;
            ltrCommentCountLabel.Text = @"<span>" + ArticleResources.BlogFeedbackLabel + @": <span class='cursor feedbacktrigger" + ModuleId + @"'>" + article.CommentCount + @"</span> |</span>";
            ltrCommentCountLabel.Visible = config.AllowComments;

            litStartDate.Text = timeZone != null ? TimeZoneInfo.ConvertTimeFromUtc(article.StartDate, timeZone).ToString(config.DateTimeFormat) : article.StartDate.AddHours(TimeOffset).ToString(config.DateTimeFormat);
            litStartDate.Visible = config.DateTimeFormat != string.Empty;

            odiogoPlayer.OdiogoFeedId = config.OdiogoFeedId;
            odiogoPlayer.ItemId = article.ItemId.ToString(CultureInfo.InvariantCulture);
            odiogoPlayer.ItemTitle = article.Title;
            if (blogAuthor.Length == 0) { blogAuthor = article.UserName; }
            litAuthor.Text = ArticleUtils.FormatPostAuthor(article.UserGuid.ToString(), config);
            litDescription.Text = article.Description;
            litExcerpt.Text = GetExcerpt(article);

            if (article.PreviousPostUrl.Length > 0)
            {
                lnkPreviousPostTop.Visible = true;
                lnkPreviousPost.Visible = true;
                lnkPreviousPostTop.NavigateUrl = basePage.SiteRoot + article.PreviousPostUrl.Replace("~", string.Empty);
                lnkPreviousPostTop.ToolTip = article.PreviousPostTitle;

                lnkPreviousPost.NavigateUrl = basePage.SiteRoot + article.PreviousPostUrl.Replace("~", string.Empty);
                lnkPreviousPost.ToolTip = article.PreviousPostTitle;

            }

            if (article.NextPostUrl.Length > 0)
            {
                lnkNextPostTop.Visible = true;
                lnkNextPost.Visible = true;
                lnkNextPostTop.NavigateUrl = basePage.SiteRoot + article.NextPostUrl.Replace("~", string.Empty);
                lnkNextPostTop.ToolTip = article.NextPostTitle;

                lnkNextPost.NavigateUrl = basePage.SiteRoot + article.NextPostUrl.Replace("~", string.Empty);
                lnkNextPost.ToolTip = article.NextPostTitle;
            }

            if (article.Location.Length > 0)
            {
                gmap.Visible = true;
                gmap.GMapApiKey = GmapApiKey;
                gmap.Location = article.Location;
                gmap.EnableMapType = config.GoogleMapEnableMapType;
                gmap.EnableZoom = config.GoogleMapEnableZoom;
                gmap.ShowInfoWindow = config.GoogleMapShowInfoWindow;
                gmap.EnableLocalSearch = config.GoogleMapEnableLocalSearch;
                gmap.MapHeight = config.GoogleMapHeight;
                gmap.MapWidth = config.GoogleMapWidth;
                gmap.EnableDrivingDirections = config.GoogleMapEnableDirections;
                gmap.GmapType = config.GoogleMapType;
                gmap.ZoomLevel = config.GoogleMapInitialZoom;
                gmap.DirectionsButtonText = ArticleResources.MapGetDirectionsButton;
                gmap.DirectionsButtonToolTip = ArticleResources.MapGetDirectionsButton;
            }

            using (IDataReader dataReader = Article.GetBlogComments(ModuleId, ItemId))
            {
                dlComments.DataSource = dataReader;
                dlComments.DataBind();
            }
            BindAttachments();
            PopulateNavigation();

            if (Page.Header == null) { return; }

            Literal link = new Literal
                               {
                                   ID = "blogurl",
                                   Text = @"<link rel='canonical' href='"
                                          + SiteRoot
                                          + article.ItemUrl.Replace("~/", "/")
                                          + @"' />"
                               };

            Page.Header.Controls.Add(link);

            if (category != null && !string.IsNullOrEmpty(category.Category))  
            {
                List<ud_ArticleCategory> listParent = new List<ud_ArticleCategory>();
                repository.GetParentCategory(category.CategoryID, ref listParent);
                if (listParent.Count > 0)
                {
                    foreach (ud_ArticleCategory articleCategory in listParent)
                    {
                        Title1.Header = articleCategory.Category + " > " + Title1.Header;
                    }
                    Title1.Header += category.Category;
                }
                else
                {
                    Title1.Header = category.Category;
                }
            }
            else
            {
                Title1.Header = Utilities.RemoveTwoColorModuleTitleText(module.ModuleTitle);
            }
            BindOtherArticles();
            lblHitCountLabel.Text = article.HitCount.ToString();
        }

        protected string BuildDownloadLink(string id, string name)
        {
            string innerMarkup = name;
            if (config.UseAttachmentDownloadIconSetting)
            {
                innerMarkup = "<img src='" + ImageSiteRoot + "/Data/SiteImages/Download.gif' alt='" + ArticleResources.DownloadLink + "' />";
            }

            return "<a href='" + SiteRoot + "/Article/Download.aspx?pageid=" + PageId.ToInvariantString()
                + "&amp;mid=" + ModuleId.ToInvariantString()
                + "&amp;fileid=" + id + "' "
                + "title='" + name + "' "
                + newWindowMarkup
                + ">"
                + innerMarkup
                + "</a>";
        }

        void rptAttachments_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Image imgType = (Image)e.Item.FindControl("imgType");
            if (imgType == null) return;
            string name = DataBinder.Eval(e.Item.DataItem, "q.FileName", "{0}").Trim();
            // ReSharper disable PossibleNullReferenceException
            string imgFile = Path.GetExtension(name).ToLower().Replace(".", "") + ".png";
            string path = Request.PhysicalApplicationPath + "/Data/SiteImages/Icons/" + imgFile;
            if (File.Exists(path))
            {
                imgType.ImageUrl = ImageSiteRoot + "/Data/SiteImages/Icons/" + imgFile;
            }
            // ReSharper restore PossibleNullReferenceException
        }

        private void BindAttachments()
        {
            DBArticleAttachment repositoryAttachment = new DBArticleAttachment();
            rptAttachments.DataSource = repositoryAttachment.GetByItemID(ItemId);
            rptAttachments.DataBind();
            if(rptAttachments.Items.Count == 0)
            {
                pnlAttachment.Visible = false;
            }
        }
        private void BindOtherArticles()
        {
            DBArticleLinq repositoryArticle = new DBArticleLinq();
            otherArticles = category != null && category.CategoryID != null && category.CategoryID > 0
                                ? repositoryArticle.GetOtherArticlesByItemID(ItemId, ModuleId, category.CategoryID)
                                : repositoryArticle.GetOtherArticlesByItemID(ItemId, ModuleId);
            lvOtherArticles.DataSource = otherArticles;
            lvOtherArticles.DataBind();
            if (otherArticles.Count.Equals(0))
            { pnlOther.Visible = false; }
            if (otherArticles.Count <= config.OtherArticlesDetailPageSizeSetting)
            { pnlOtherPager.Visible = false; }
        }

        protected virtual void PopulateNavigation()
        {
            Feeds.Config = config;
            Feeds.PageId = PageId;
            Feeds.ModuleId = ModuleId;
            Feeds.Visible = config.ShowFeedLinks;

            if (config.ShowCategories)
            {
                tags.CanEdit = IsEditable;
                tags.PageId = PageId;
                tags.ModuleId = ModuleId;
                tags.SiteRoot = SiteRoot;
                tags.RenderAsTagCloud = config.UseTagCloudForCategories;
            }
            else
            {
                pnlCategories.Visible = false;
                tags.Visible = false;
            }

            if (config.ShowArchives)
            {
                archive.PageId = PageId;
                archive.ModuleId = ModuleId;
                archive.SiteRoot = SiteRoot;
            }
            else
            {
                archive.Visible = false;
                pnlArchives.Visible = false;
            }

            int countOfDrafts = Article.CountOfDrafts(ModuleId);

            stats.PageId = PageId;
            stats.ModuleId = ModuleId;
            stats.CountOfDrafts = countOfDrafts;
            stats.Visible = config.ShowStatistics;

        }

        private void btnPostComment_Click(object sender, EventArgs e)
        {
            if (!AllowComments)
            {
                WebUtils.SetupRedirect(this, Request.RawUrl);
                return;
            }
            if (!IsValidComment())
            {
                PopulateControls();
                return;
            }
            if (article == null) { return; }

            if (article.AllowCommentsForDays < 0)
            {
                WebUtils.SetupRedirect(this, Request.RawUrl);
                return;
            }

            DateTime endDate = article.StartDate.AddDays(article.AllowCommentsForDays);

            if ((endDate < DateTime.UtcNow) && (article.AllowCommentsForDays > 0)) return;

            if (chkRememberMe.Checked)
            {
                SetCookies();
            }

            Article.AddBlogComment(
                    ModuleId,
                    ItemId,
                    txtName.Text,
                    txtCommentTitle.Text,
                    txtURL.Text,
                    edComment.Text,
                    DateTime.UtcNow);

            if ((config.NotifyOnComment) && (Email.IsValidEmailAddressSyntax(config.NotifyEmail)))
            {
                //added this 2008-08-07 due to blog coment spam and need to be able to ban the ip of the spammer
                StringBuilder message = new StringBuilder();
                message.Append(basePage.SiteRoot + article.ItemUrl.Replace("~", string.Empty));

                message.Append("\n\nHTTP_USER_AGENT: " + Page.Request.ServerVariables["HTTP_USER_AGENT"] + "\n");
                message.Append("HTTP_HOST: " + Page.Request.ServerVariables["HTTP_HOST"] + "\n");
                message.Append("REMOTE_HOST: " + Page.Request.ServerVariables["REMOTE_HOST"] + "\n");
                message.Append("REMOTE_ADDR: " + SiteUtils.GetIP4Address() + "\n");
                message.Append("LOCAL_ADDR: " + Page.Request.ServerVariables["LOCAL_ADDR"] + "\n");
                message.Append("HTTP_REFERER: " + Page.Request.ServerVariables["HTTP_REFERER"] + "\n");

                Notification.SendBlogCommentNotificationEmail(
                    SiteUtils.GetSmtpSettings(),
                    ResourceHelper.GetMessageTemplate(ResourceHelper.GetDefaultCulture(), "BlogCommentNotificationEmail.config"),
                    basePage.SiteInfo.DefaultEmailFromAddress,
                    basePage.SiteRoot,
                    config.NotifyEmail,
                    message.ToString());


            }

            WebUtils.SetupRedirect(this, Request.RawUrl);

        }

        private void PopulateLabels()
        {
            ltrBack.Text = @"<a href='javascript: history.go(-1)'><img src=" + ImageSiteRoot + @"/Data/Icon16x16/Back.png /> " + ArticleResources.ButtonBack + @" </a>";

            lnkEdit.ToolTip = ArticleResources.BlogEditEntryLink;
            pnlImageWrapper.Visible = config.ShowImageInViewPostSetting;
            regexUrl.ErrorMessage = ArticleResources.WebSiteUrlRegexWarning;
            dpOtherArticles.PageSize = config.OtherArticlesDetailPageSizeSetting;

            pnlAttachment.Visible = config.UseAttachmentSetting;
            lblAttachments.Visible = config.ShowAttachmentLabelSetting;

            pnlFeedbackTrigger.CssClass += " feedbacktrigger" + ModuleId;
            pnlFeedback.CssClass += " feedback" + ModuleId;
            pnlFeedbackTrigger.Visible = config.AllowComments;
            pnlFeedbackTrigger.ToolTip = ArticleResources.PostComment;

            btnPostComment.Text = ArticleResources.BlogCommentPostCommentButton;
            SiteUtils.SetButtonAccessKey(btnPostComment, ArticleResources.BlogCommentPostCommentButtonAccessKey);

            litCommentsClosed.Text = ArticleResources.BlogCommentsClosedMessage;
            litCommentsRequireAuthentication.Text = ArticleResources.CommentsRequireAuthenticationMessage;

            lnkPreviousPostTop.Text = Server.HtmlEncode(ArticleResources.BlogPreviousPostLink);
            lnkNextPostTop.Text = Server.HtmlEncode(ArticleResources.BlogNextPostLink);

            lnkPreviousPost.Text = Server.HtmlEncode(ArticleResources.BlogPreviousPostLink);
            lnkNextPost.Text = Server.HtmlEncode(ArticleResources.BlogNextPostLink);

            lblOtherHeader.Text = config.OtherArticle;

            Image imgProgress = upProgress1.FindControl("imgProgress") as Image;
            if (imgProgress == null) return;
            imgProgress.ImageUrl = ImageSiteRoot + "/Data/Icon16x16/updateprogress.gif";
            imgProgress.AlternateText = ArticleResources.Loading;
        }

        private void LoadSettings()
        {
            if (ItemId != -1)
            {
                article = new Article(ItemId);
                category = repository.GetOneByArticleID(article.ItemId);
                article.Save();
            }
            module = basePage.GetModule(ModuleId);

            if (
                (module.ModuleId == -1)
                || (article.ModuleId == -1)
                || (article.ModuleId != module.ModuleId)
                || (basePage.SiteInfo == null)
                )
            {
                // query string params have been manipulated
                pnlBlog.Visible = false;
                AllowComments = false;
                parametersAreInvalid = true;
                return;
            }

            RegexRelativeImageUrlPatern = SecurityHelper.RegexRelativeImageUrlPatern;

            moduleSettings = ModuleSettings.GetModuleSettings(ModuleId);

            config = new ArticleConfiguration(moduleSettings);

            GmapApiKey = SiteUtils.GetGmapApiKey();

            DisqusSiteShortName = config.DisqusSiteShortName.Length > 0 ? config.DisqusSiteShortName : basePage.SiteInfo.DisqusSiteShortName;

            IntenseDebateAccountId = config.IntenseDebateAccountId.Length > 0 ? config.IntenseDebateAccountId : basePage.SiteInfo.IntenseDebateAccountId;
            
            if (config.InstanceCssClass.Length > 0)
            {
                pnlBlog.CssClass += config.InstanceCssClass.Contains(" ")
                                        ? " " + config.InstanceCssClass.Remove(config.InstanceCssClass.IndexOf(" ")) +
                                          "-detail"
                                        : " " + config.InstanceCssClass + "-detail";
            }

            CommentDateTimeFormat = config.DateTimeFormat;

            divCommentUrl.Visible = config.AllowWebSiteUrlForComments;

            Rating.Enabled = config.EnableContentRating;
            Rating.AllowFeedback = config.EnableRatingComments;
            Rating.ContentGuid = article.BlogGuid;

            lblCopyright.Text = config.Copyright;


            AllowComments = config.AllowComments;

            litAuthor.Visible = config.ShowPostAuthor;

            pnlStatistics.Visible = config.ShowStatistics;
            pnlFeedback.Visible = AllowComments;

            if (!config.NavigationOnRight)
            {
                divNav.CssClass = "blognavleft";
                divblog.CssClass = "blogcenter-leftnav";

            }

            divNav.Visible = false;
            if (config.ShowArchives
                || config.ShowAddFeedLinks
                || config.ShowCategories
                || config.ShowFeedLinks
                || config.ShowStatistics)
            {
                divNav.Visible = true;
            }

            if (!divNav.Visible)
            {
                divblog.CssClass = "blogcenter-nonav";
            }

            if (article.AllowCommentsForDays < 0)
            {
                pnlNewComment.Visible = false;
                pnlCommentsClosed.Visible = true;
                AllowComments = false;
            }

            if (article.AllowCommentsForDays == 0)
            {
                pnlNewComment.Visible = true;
                pnlCommentsClosed.Visible = false;
                AllowComments = true;
            }

            if (article.AllowCommentsForDays > 0)
            {
                DateTime endDate = article.StartDate.AddDays(article.AllowCommentsForDays);

                if (endDate > DateTime.UtcNow)
                {
                    pnlNewComment.Visible = true;
                    pnlCommentsClosed.Visible = false;
                    AllowComments = true;
                }
                else
                {
                    pnlNewComment.Visible = false;
                    pnlCommentsClosed.Visible = true;
                    AllowComments = false;
                }
            }

            if (AllowComments)
            {
                if ((config.RequireAuthenticationForComments) && (!Request.IsAuthenticated))
                {
                    AllowComments = false;
                    pnlNewComment.Visible = false;
                    pnlCommentsRequireAuthentication.Visible = true;
                }

            }

            if (!config.UseCaptcha)
            {
                pnlAntiSpam.Visible = false;
                captcha.Visible = false;
                captcha.Enabled = false;
                //pnlNewComment.Controls.Remove(captcha);
            }



            if (AllowComments)
            {
                if ((config.CommentSystem == "disqus") && (DisqusSiteShortName.Length > 0))
                {

                    // don't use new external comment system for existing posts that already have comments
                    if (article.CommentCount == 0)
                    {
                        disqus.SiteShortName = DisqusSiteShortName;
                        disqus.RenderWidget = true;
                        disqus.WidgetPageUrl = FormatBlogUrl(article.ItemUrl, article.ItemId);
                        //disqus.WidgetPageId = blog.BlogGuid.ToString();
                        pnlFeedback.Visible = false;
                        if (config.UseCaptcha)
                        {
                            pnlAntiSpam.Visible = false;
                            captcha.Visible = false;
                            captcha.Enabled = false;
                            //Controls.Remove(pnlAntiSpam); 
                        }
                    }

                    stats.ShowCommentCount = false;

                }

                if ((config.CommentSystem == "intensedebate") && (IntenseDebateAccountId.Length > 0))
                {
                    if (article.CommentCount == 0)
                    {
                        intenseDebate.AccountId = IntenseDebateAccountId;
                        intenseDebate.PostUrl = FormatBlogUrl(article.ItemUrl, article.ItemId);
                        pnlFeedback.Visible = false;
                        if (config.UseCaptcha)
                        {
                            pnlAntiSpam.Visible = false;
                            captcha.Visible = false;
                            captcha.Enabled = false;
                            //Controls.Remove(pnlAntiSpam); 
                        }
                    }
                    stats.ShowCommentCount = false;
                }
            }




            if (Request.IsAuthenticated)
            {
                SiteUser currentUser = SiteUtils.GetCurrentSiteUser();
                txtName.Text = currentUser.Name;
                txtURL.Text = currentUser.WebSiteUrl;

            }
            else
            {
                if ((config.HideDetailsFromUnauthencticated) && (article.Description.Length > config.ExcerptLength))
                {
                    pnlDetails.Visible = false;
                    pnlExcerpt.Visible = true;
                }

                if (CookieHelper.CookieExists("blogUser"))
                {
                    txtName.Text = CookieHelper.GetCookieValue("blogUser");
                }
                if (CookieHelper.CookieExists("blogUrl"))
                {
                    txtURL.Text = CookieHelper.GetCookieValue("blogUrl");
                }
            }

        }

        private string GetExcerpt(Article itemArticle)
        {
            if ((itemArticle.Excerpt.Length > 0) && (itemArticle.Excerpt != "<p>&#160;</p>"))
            {
                return itemArticle.Excerpt;
            }
            itemArticle.Description = SecurityHelper.RemoveMarkup(itemArticle.Description);
            return (itemArticle.Description.Length > config.ExcerptLength) ? UIHelper.CreateExcerpt(itemArticle.Description, config.ExcerptLength, config.ExcerptSuffix) : article.Description;
        }

        protected string FormatCommentDate(DateTime startDate)
        {
            string result = " (";
            result += timeZone != null ? TimeZoneInfo.ConvertTimeFromUtc(startDate, timeZone).ToString(CommentDateTimeFormat) : startDate.AddHours(TimeOffset).ToString(config.DateTimeFormat);
            result += ")";
            return result;
        }

        protected string FormatBlogUrl(string itemUrl, int itemId)
        {
            if (itemUrl.Length > 0)
                return SiteRoot + itemUrl.Replace("~", string.Empty);

            return SiteRoot + "/Article/ViewPost.aspx?pageid=" + PageId.ToInvariantString()
                + "&ItemID=" + itemId.ToInvariantString()
                + "&mid=" + ModuleId.ToInvariantString();

        }




        private bool IsValidComment()
        {
            if (parametersAreInvalid) { return false; }

            if (!AllowComments) { return false; }

            if ((config.CommentSystem != "internal") && (article.CommentCount == 0)) { return false; }

            if (edComment.Text.Length == 0)
            {
                lblCommentError.Visible = true;
                return false;
            }
            lblCommentError.Visible = false;
            if (edComment.Text == @"<p>&#160;</p>")
            {
                lblCommentError.Visible = true;
                return false;
            }
            lblCommentError.Visible = false;
            bool result = true;

            try
            {
                Page.Validate("blogcomments");
                result = Page.IsValid;

            }
            catch (NullReferenceException)
            {
                //Recaptcha throws nullReference here if it is not visible/disabled
            }
            catch (ArgumentNullException)
            {
                //manipulation can make the Challenge null on recaptcha
            }


            try
            {
                if ((result) && (config.UseCaptcha))
                {
                    result = captcha.IsValid;
                }
            }
            catch (NullReferenceException)
            {
                return false;
            }
            catch (ArgumentNullException)
            {
                //manipulation can make the Challenge null on recaptcha
                return false;
            }


            return result;
        }

        /// <summary>
        /// Handles the item command
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        protected void dlComments_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "DeleteComment")
            {
                Article.DeleteBlogComment(int.Parse(e.CommandArgument.ToString()));
                WebUtils.SetupRedirect(this, Request.RawUrl);

            }
        }


        void dlComments_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            ImageButton btnDelete = e.Item.FindControl("btnDelete") as ImageButton;
            UIHelper.AddConfirmationDialog(btnDelete, ArticleResources.BlogDeleteCommentWarning);
        }


        private void SetCookies()
        {
            HttpCookie blogUserCookie = new HttpCookie("blogUser", txtName.Text) {Expires = DateTime.Now.AddMonths(1)};
            Response.Cookies.Add(blogUserCookie);

            HttpCookie blogUrlCookie = new HttpCookie("LinkUrl", txtURL.Text) {Expires = DateTime.Now.AddMonths(1)};
            Response.Cookies.Add(blogUrlCookie);
        }


        protected virtual void SetupRssLink()
        {
            if (WebConfigSettings.DisableBlogRssMetaLink) { return; }

            if (module != null)
            {
                if (Page.Master != null)
                {
                    Control head = Page.Master.FindControl("Head1");
                    if (head != null)
                    {

                        Literal rssLink = new Literal
                                              {
                                                  Text = @"<link rel=""alternate"" type=""application/rss+xml"" title="""
                                                         + module.ModuleTitle + @""" href="""
                                                         + GetRssUrl() + @""" />"
                                              };

                        head.Controls.Add(rssLink);

                    }

                }
            }

        }

        private string GetRssUrl()
        {
            if (config.FeedburnerFeedUrl.Length > 0) return config.FeedburnerFeedUrl;

            return SiteRoot + "/blog" + ModuleId.ToInvariantString() + "rss.aspx";

        }

        private void LoadParams()
        {
            WebUtils.GetApplicationRoot();
            TimeOffset = SiteUtils.GetUserTimeOffset();
            timeZone = SiteUtils.GetUserTimeZone();
            PageId = WebUtils.ParseInt32FromQueryString("pageid", -1);
            ModuleId = WebUtils.ParseInt32FromQueryString("mid", -1);
            ItemId = WebUtils.ParseInt32FromQueryString("ItemID", -1);

            if (PageId == -1) parametersAreInvalid = true;
            if (ModuleId == -1) parametersAreInvalid = true;
            if (ItemId == -1) parametersAreInvalid = true;
            if (!basePage.UserCanViewPage(ModuleId)) { parametersAreInvalid = true; }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if ((Page.IsPostBack) && (!pnlFeedback.Visible))
            {
                //WebUtils.SetupRedirect(this, Request.RawUrl);
                //return;
            }

            base.Render(writer);
        }

        protected string FormatTooltip(string title, string content)
        {
            string result;
            if (config.UseTooltipSettings)
            {
                if (content.Length > config.TooltipMaxCharSettings)
                {
                    content = UIHelper.CreateExcerpt(content, config.TooltipMaxCharSettings, "...");
                }
                result = "<div class='tooltip'><div class='title-l'></div><div class='title-m'>" + title + "</div><div class='title-r'></div><div class='body'>" + content + "</div></div>";
            }
            else
            {
                result = title;
            }
            return result;
        }

        protected string FormatBlogTitleUrl(string itemUrl, int itemId)
        {
            if (itemUrl.Length > 0)
                return SiteRoot + itemUrl.Replace("~", string.Empty);

            return SiteRoot + "/Article/ViewPost.aspx?pageid=" + PageId.ToInvariantString()
                + "&ItemID=" + itemId.ToInvariantString()
                + "&mid=" + ModuleId.ToInvariantString();

        }
    }
}